   #!/usr/bin/env python

import os
import sys
import pygtk
import gtk
import gtk.glade
import serial
import time
import gobject
import pango
import math
from string import *


from visual import *

import gtk.gdk as gdk
from threading import Thread, Lock
from thread import error as thread_error


file_name= ""
Seite = ""


nlines = 0
line=0
templine = 0

connected = False
warte  = False
counter = 0
stop= False
G90gesendet=False
antwort=""

scene2 = display(title='GCode View',
           x=500, y=50, width=600, height=400,
           center=(0,2,3), background=color.black)

element = [curve(color=color.white)]

elementzaehler = 0
stext=label(pos=(0,-20,0), opacity=1, box=0, line=0)


############# USB suchen


#### fuer windows

if (os.name=='nt') :

  
  while  ((counter<10) and not connected):
   counter += 1
   com_port= "COM%i" % counter
   print com_port
   try:
    time.sleep(0.6)     
    ser = serial.Serial(com_port, 115200, timeout=1)
    
    ser.write("G21 \n")
    antwort=ser.readline().strip()
    #print ("antwort: "+antwort)
    if antwort=="ok":
        # x y z send from arduino
        ser.readline()
        ser.readline()
        ser.readline()
        connected = True
       
   except:
    connected = False

 #### fuer linux ######

else:    
        
 locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3',  
  '/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3']  

 for com_port in locations:  

  try:
    ser = serial.Serial(com_port,115200)
    ser.write("G21 \n")
    if ser.readline().strip()=="ok":
        # x y z send from arduino
        ser.readline()
        ser.readline()
        ser.readline()
        connected = True
        break
  except:
    connected = False 

        

############# USB Suchen ende 

wTree = gtk.glade.XML("axcnc.glade" ,"mainWindow")


class mclick (Thread):
      
   def __init__(self, Id):
    self.Id = Id
    self.ctrl = True
    self.Running = False
    self.ShowMode = 0
    self.lock = Lock()
    self.lock.acquire()
    Thread.__init__(self)
    warte = False
  #end __init__

   def run(self):
       
    global elementzaehler
    global Seite
    global stext
    global element
    
    while True:
       if scene2.mouse.clicked:
                m = scene2.mouse.getclick()
                scene2.center=m.pos
       if  scene2.kb.keys:
                k = scene2.kb.getkey()
                elementzaehler = elementzaehler+1
                stext.visible=False
                stext=label(pos=(0,-20,0), text="Zeile Nr= %i " % elementzaehler
                            +"\n "+Seite[elementzaehler-1]  , opacity=1, box=0, line=0)
                stext.visible= True
                element[elementzaehler].color=color.red
                        
  
   def Start(self,ignore):
      try:
        self.lock.release()
      except thread_error:
        pass
   




class Counting (Thread):
 
  def __init__(self, Id):
    self.Id = Id
    self.ctrl = True
    self.Running = False
    self.ShowMode = 0
    self.lock = Lock()
    self.lock.acquire()
    Thread.__init__(self)
    warte = False
  #end __init__

  def run(self):
    global file_name
    global Seite
    global nlines
    global line
    global templine
    global warte
     
    while 1:


           #time.sleep(1)
           
           if not self.Running:
             self.lock.acquire()
             self.Running = True

           if not self.ctrl:
             return

           if (templine>= nlines):
               gdk.threads_enter()
               aline=templine+1
               zeige_info('Ready' )  
               gdk.threads_leave()
               self.Running = False            

           if ((templine< nlines) and not warte):
               gdk.threads_enter()
               zeile = Seite[templine]
               aline=templine+1
               zeige_info('send %i: ' %aline +zeile)
               ser.write(zeile)
               gdk.threads_leave()                
               templine += 1
               
           antwort= ser.readline()
           
           if (not(antwort)and (templine< nlines)):
               gdk.threads_enter()
               zeige_info(".")
               #time.sleep(0.5)
               warte = True
               gdk.threads_leave() 
             
   
           if strip(antwort)== "Break" :
                  gdk.threads_enter()
                  zeige_info(" Break !")
                  Koordinaten_anzeigen()
                  gdk.threads_leave()  
                  templine=nlines
                  warte = False
                  self.Running = False    
                                

           if strip(antwort)== "ok" :
                   gdk.threads_enter()
                   zeige_info(" ok\n ")
                   Koordinaten_anzeigen()
                   warte= False
                   gdk.threads_leave() 
                   
           else:
             if  antwort :
                        gdk.threads_enter()
                        zeige_info("? = "+antwort)
#Nur fuer test 
#                        warte = True
#Nur fuer test damit alle Infos angezeigt werden 
            
                        gdk.threads_leave() 

  
  #end run

  def Start(self,ignore):
 
## Stop    
##    if self.Running:
##      self.Running = False
##    else:
      try:
        self.lock.release()
      except thread_error:
        pass
    #end if
  #end Start_Stop



  def Quit(self,ignore):
    #print "quit"
    self.ctrl = False
    if not self.Running:
      released = False
      while not released:
        try:
          self.lock.release()
          released = True
        except thread_error:
          pass
        #end try
      #end while
    #end if
  #end Quit
        
#end Counting

Worker = Counting(1)
Worker.start()


def zeige_info(txt):

## Windos
     # print (strip(txt))

      buffer = wTree.get_widget("info").get_buffer()
      buffer.insert_at_cursor(txt)
      wTree.get_widget("info").scroll_mark_onscreen(buffer.get_insert())

def Koordinaten_anzeigen():

##     ## Windows 
##       # x lesen
##       antwort= strip(ser.readline())
##       print("xanzeige "+antwort)
##       # y lesen
##       antwort= strip(ser.readline())
##       print("yanzeige "+antwort)
##       #z lesen
##       antwort= strip(ser.readline())
##       print ("zanzeige "+antwort)


  
     ##Linux 
       # x lesen
       antwort= strip(ser.readline())
       wTree.get_widget("xanzeige").set_text(antwort)
       # y lesen
       antwort= strip(ser.readline())
       wTree.get_widget("yanzeige").set_text(antwort)	
       #z lesen
       antwort= strip(ser.readline())
       wTree.get_widget("zanzeige").set_text(antwort)


 

def send_line(txline):
       global connected
       global stop
            
       if connected:
            if (os.name=='nt') :
             #LesePuffer leeren da noch ok und koordinaten kommt
             antwort="x"  
             while antwort :
                antwort= ser.readline()
                     
            zeige_info( "send_line = " + txline+" \n"  ) 
            ser.write(txline)

            time.sleep(0.5)
            antwort =""
            while not antwort:
                antwort= ser.readline()           
                if (not(antwort)):
                   zeige_info(".")
                if strip(antwort)== "Break" :
                  zeige_info(" Break !")
                  Koordinaten_anzeigen()
                  if (os.name=='nt') :
                   #LesePuffer leeren da noch ok und koordinaten kommt
                   antwort="x"  
                   while antwort :
                    antwort= ser.readline()
              
                  BreakDlg = BreakDialog();		
                  result = BreakDlg.run()
                  if (result == gtk.RESPONSE_OK):
                      zeige_info("weiter")
                      ser.write("G27 \n") # Spezialbefehl um Restweg zu gehen
                      time.sleep(0.5)
                      antwort=""     # um while weiterzumachen
                  else :
                      stop=True
                      break     
                  
                if strip(antwort)== "ok" :
                  zeige_info(" ok\n ")
                  Koordinaten_anzeigen()
                else:
                  if  antwort :
                        zeige_info("? = "+antwort)
                        antwort=""
     
       else:  zeige_info("not Connected\n")
    

class BreakDialog:
	
    def __init__(self):
	
		#setup the glade file
          self.gladefile = "axcnc.glade"

    def run(self):
	  #load the dialog from the glade file	  
          self.wTree = gtk.glade.XML(self.gladefile, "BreakDlg")
          #Get the actual dialog widget
          self.dlg = self.wTree.get_widget("BreakDlg")
          #run the dialog and store the response		
          self.result = self.dlg.run()
	  #we are done with the dialog, destory it
          self.dlg.destroy()
          return self.result

class PlayDialog:

    global nlines
    global line

    def __init__(self):
	
	  #setup the glade file
          self.gladefile = "axcnc.glade"

    def run(self):
          global nlines
          global line
       
	  #load the dialog from the glade file	  
          self.wTree = gtk.glade.XML(self.gladefile, "playdlg")
          #Get the actual dialog widget
          self.dlg = self.wTree.get_widget("playdlg")

          self.fromline = self.wTree.get_widget("fromline")
          line=line+1
          linestr=" %i " % line
          self.fromline.set_text(linestr)
          self.toline = self.wTree.get_widget("toline")
          nlinesstr=" %i " % nlines
          self.toline.set_text(nlinesstr)


          #run the dialog and store the response
          self.result = self.dlg.run()
          linestr=self.fromline.get_text()
          line= int(linestr)
          line= line-1
          nlinesstr=self.toline.get_text()
          nlines= int(nlinesstr)
	  #we are done with the dialog, destory it
          self.dlg.destroy()
          return self.result,line,nlines

class pygcode:
        global com_port
                        
        def __init__(self):			
                global connected
                global Seite
              
                befehle = { "on_mainWindow_destroy" : self.On_Delete,
                            "on_open1_activate"  : self.on_open1_activate,
                            "on_go_button_clicked" : self.on_go_button_clicked,
                            "on_yminus_clicked" : self.on_yminus_clicked,
                            "on_yplus_clicked" : self.on_yplus_clicked,
                            "on_xplus_clicked": self.on_xplus_clicked,
                            "on_xminus_clicked" : self.on_xminus_clicked,
                            "on_zplus_clicked": self.on_zplus_clicked,
                            "on_zminus_clicked": self.on_zminus_clicked,
                            "on_makehome_clicked": self.on_makehome_clicked,
                            "power_clicked" : self.power_clicked,
                            "on_play_clicked": self.ausfuehren_send_file}
 
                wTree.signal_autoconnect(befehle)
                self.commando  = wTree.get_widget("commando")
                self.info      = wTree.get_widget("info")
                self.textview1 = wTree.get_widget("textview1")

        
                if connected:
                        zeige_info("Connected on "+com_port+"\n")
                        zeige_info("G91 is Incremental positioning\n")
                        commando='G91 \n' 
                        send_line(commando)
  
                else:
                        zeige_info("not Connected\n")


#Test von 3D zeichnen
                        
##                file_name ="test.nc"
##                file = open(file_name,'r')
##                Seite = file.readlines()
##                file.close()
##                nlines = len(Seite)
##
##                line= 0
##                # File als Tempfile abspeichern
##                pktpos= find(file_name,".")
##                anfangfilename =  file_name[0:pktpos]
##                outfilename =  anfangfilename+".tmp"
##                file = open(outfilename, 'w')            
##                nlines = len(Seite)
##                line = 0
##                while line < nlines:
##                          zeile = Seite[line]
##
##                          # 31.03.11 wenn  ohne  J0 nur mit I wird ein zu grosses
##                          # Loch gefraest
##                          indexi  = find(zeile,"I")
##                          indexj  = find(zeile,"J")
##                          if ( (indexi) != -1)and (indexj == -1):
##                              # F wegkuerzen
##                              index  = find(zeile,"F")
##                              if ( (index) != -1):
##                                zeile = zeile[0:index]
##                              else: # \n muss weg
##                                zeile = zeile[0:(len(zeile)-2)]
##                              zeile = zeile+" J0 "+"\n"
##                          
##                          # nur Zeilen ohne Klammer bearbeiten
##                          # und groesser 3 Zeichen
##                          if ( (len(zeile)>3) and ( find(zeile,"(")  == -1) ):
##                           file.write(zeile)
##                          line += 1
##                file.close()
##                file_name=outfilename
##
##                self.G82_ersetzen(file_name)
##
##                line = 0 # von der ersten Zeile aus Zeichnen
##
##                file = open(file_name,'r')
##                Seite = file.readlines()
##                file.close()
##                nlines = len(Seite)
##                     
##                name=os.path.basename(file_name)                                 
##                wTree.get_widget("entry1").set_text(name)
##                       
##                # G file mit Zeilennummern anzeigen
##                templine=0
##                while ((templine < nlines) and not stop):
##                           zeile = Seite[templine]
##                           aline=templine+1
##                           zeilemitnr=" %i :" % aline+ zeile
##                           buffer = self.textview1.get_buffer()
##                           buffer.insert_at_cursor(zeilemitnr)
##                           self.textview1.scroll_mark_onscreen(buffer.get_insert())
##                           templine += 1
##
##                   
##                self.zeichnen(Seite)
##                
 #ende test 3D Zeichnen


 
        def on_open1_activate(self, widget):
                global file_name
                global Seite
                global nlines
                global line
                
                file_name = self.browse_for_file()
                if (file_name!=""):
                    
                        file = open(file_name,'r')
                        Seite = file.readlines()
                        file.close()
                        nlines = len(Seite)

                        line= 0
                        # File als Tempfile abspeichern
                        pktpos= find(file_name,".")
                        anfangfilename =  file_name[0:pktpos]
                        outfilename =  anfangfilename+".tmp"
                        file = open(outfilename, 'w')            
                        nlines = len(Seite)
                        line = 0
                        while line < nlines:
                          zeile = Seite[line]

                          # 31.03.11 wenn  ohne  J0 nur mit I wird ein zu grosses
                          # Loch gefraest
                          indexi  = find(zeile,"I")
                          indexj  = find(zeile,"J")
                          if ( (indexi) != -1)and (indexj == -1):
                              # F wegkuerzen
                              index  = find(zeile,"F")
                              if ( (index) != -1):
                                zeile = zeile[0:index]
                              else: # \n muss weg
                                zeile = zeile[0:(len(zeile)-2)]
                              zeile = zeile+" J0 "+"\n"
                          
                          # nur Zeilen ohne Klammer bearbeiten
                          # und groesser 3 Zeichen
                          if ( (len(zeile)>3) and ( find(zeile,"(")  == -1) ):
                           file.write(zeile)
                          line += 1
                        file.close()
                        file_name=outfilename

                        self.G82_ersetzen(file_name)
                        self.R_ersetzen(file_name)
                        line = 0 # von der ersten Zeile aus Zeichnen

                        file = open(file_name,'r')
                        Seite = file.readlines()
                        file.close()
                        nlines = len(Seite)
                        
                        name=os.path.basename(file_name)                                 
                        wTree.get_widget("entry1").set_text(name)
                       
                        # G file mit Zeilennummern anzeigen
                        templine=0
                        while ((templine < nlines) and not stop):
                           zeile = Seite[templine]
                           aline=templine+1
                           zeilemitnr=" %i :" % aline+ zeile
                           buffer = self.textview1.get_buffer()
                           buffer.insert_at_cursor(zeilemitnr)
                           self.textview1.scroll_mark_onscreen(buffer.get_insert())
                           templine += 1

                           
                        self.zeichnen(Seite)
  

        def ausfuehren_send_file(self,widget):
          global file_name
          global stop
          global nlines
          global line
          global templine
          global Seite
          global element
          global connected
          global G90gesendet
 
      
          if file_name :  # datei wurde geladen
           if connected:

            zeige_info("G90 ist Absolute Positioning\n")
            G90gesendet=True
            commando='G90 \n'
            send_line(commando)
                   
            file = open(file_name,'r')
            Seite = file.readlines()
            file.close()
               
            stop= False
            nlines = len(Seite)
            line = 0
            if (os.name=='nt') :
             #LesePuffer leeren da noch ok und koordinaten kommt
             antwort="x"  
             while antwort :
                antwort= ser.readline()
  
            playDlg = PlayDialog();		
            result,line,nlines = playDlg.run()
            if (result == gtk.RESPONSE_OK):
             templine = line
             #Thread starten
             Worker.Start(self)

            
##            while ((templine < nlines) and not stop):
##                   zeile = Seite[templine]
##                   aline=templine+1
##                   zeige_info("line %i" % aline+ " from %i" %nlines+"\n")
##                   send_line(zeile)
##                   templine += 1
##            zeige_info('Ready !')
           else:  zeige_info("not Connected\n")
          else:  zeige_info('no file loaded !')
          # end  ausfuehren_send_file

    
        def zeichnen(self,Seite) :
           global scene2
           global element

           scene2.select()
           scene2.exit=False
           
           xachse = arrow( pos= (0,0,0) , axis=(10,0,0),color=color.yellow,
                           shaftwidth=0.7,length=12)
           yachse = arrow( pos= (0,0,0) , axis=(0,10,0),color=color.yellow,
                           shaftwidth=0.7,length=12)
           zachse = arrow( pos= (0,0,0) , axis=(0,0,10),color=color.yellow,
                           shaftwidth=0.7,length=12)
           if (os.name=='nt') :
               xb= text(text="X",pos=(12,-3,0),height=2)
               yb= text(text="Y",pos=(-3,12,0),height=2)
               zb= text(text="Z",pos=(0,-3,12),height=2)

                             
           richtigelaenge = len(Seite)

           x=0
           y=0
           z=0
           xmax=0
           ymax=0
           xmin=1000
           ymin=1000
           templine =0 
           # min max finden
           while (templine < richtigelaenge):
                     zeile = Seite[templine]
                          
                     aline=templine+1

                     #print ("zeilen nr= %i " % aline )
                     #print zeile

                     # F wegkuerzen
                     index  = find(zeile,"F")
                     if ( (index) != -1):
                       zeile = zeile[0:index]

                     # M wegkuerzen
                     index  = find(zeile,"M")
                     if ( (index) != -1):
                       zeile = zeile[0:index]

                     # S wegkuerzen
                     index  = find(zeile,"S")
                     if ( (index) != -1):
                       zeile = zeile[0:index]
                      
                     # I wegkuerzen
                     index  = find(zeile,"I")
                     if ( (index) != -1):
                       zeile = zeile[0:index]
                      
                     indexz = find(zeile,"Z")
                     if ( (indexz) != -1):
                      z= float(zeile[indexz+1:-1])
                      zeile = zeile[1:indexz]
                     indexy = find(zeile,"Y")
                     if ( (indexy) != -1):
                       y= float(zeile[indexy+1:-1])
                       zeile = zeile[1:indexy]
                     indexx = find(zeile,"X")
                     if ( (indexx) != -1):
                         x= float(zeile[indexx+1:-1])

                     if (xmax<x) : xmax=x
                     if ((xmin>x) and not(templine==0)): xmin=x
                     if (ymax<y) : ymax=y
                     if ((ymin>y) and not(templine==0)) : ymin=y
 
                     templine += 1

                  # end while

           if (os.name=='nt') :
               tmax= text(text="xmax= %.0f ," %xmax+"ymax= %.0f" %ymax,pos=(xmax,ymax,0),height=2)
        
           
##               wTree.get_widget("maxwerte").set_text("xmax %f mm " % xmax+", ymax %f mm " % ymax)
##               wTree.get_widget("minwerte").set_text("xmin %f mm " % xmin+", ymin %f mm " % ymin)
## 
##               if (xmax>ymax): maxwert= xmax
##               else :maxwert= ymax
##
##               if (xmin<ymin): minwert= abs(xmin)
##               else :minwert= abs(ymin)
##               ymin= abs(ymin)
##               xmin= abs(xmin)
##
##               absx= xmin+xmax
##               absy= ymin+ymax
##
##               if (absx>absy): absmax = absx
##               else :absmax = absy
##  
##               masstab= 230/ absmax
##
##               xaltpix=math.trunc(xmin*masstab)
##               yaltpix=math.trunc(ymin*masstab)
##
##  
############################################################
               # eigentliches Zeichnen

           x=0
           y=0
           xalt=0
           yalt=0
           zalt=0
           z=0
           templine = 0
           nlines  = len(Seite)

               
           while ((templine < nlines) ):
                      zeile = Seite[templine] 
                      aline=templine+1
                      #print ("zeilen nr= %i " % aline )
                      #print zeile

                      element.append(curve(color=color.white))
                      element[aline].append(pos=(xalt,yalt,zalt))

                    
                      
##                      stext=label(pos=(0,-20,0), text="zeilen nr= %i " % aline
##                                   +"\n "+zeile , opacity=1, box=0, line=0)
##                      stext.visible=True


                      # nur Zeilen ohne Klammer bearbeiten
                      if  (   (find(zeile,"(") ) == -1) :
                                               
                       # S wegkuerzen
                       indes  = find(zeile,"S")
                       if ( (indes) != -1):
                         zeile = zeile[0:indes]
 

                       # M funktion wegkuerzen
                       indexm  = find(zeile,"M")
                       if ( (indexm) != -1):
                         #print ("Zeile mit M funktion " )
                         zeile = zeile[1:indexm]
                         #print zeile


                       # F wegkuerzen
                       indexf  = find(zeile,"F")
                       if ( (indexf) != -1):
                         zeile = zeile[0:indexf]


                       indexi  = find(zeile,"I")
                       if ( (indexi) != -1):
                        # Kreis  zeichnen
                        # eigentlich besser ueber G02 erkennbar als uber I 
                        # G02 X-1 Y0 I-1 J0 (Zielkoordinate, Kreismittelpunkt relativ zum Startpunkt)
                        # I Abstand vom Startpunkt zum Bogenzentrum in X
                        # J Abstand vom Startpunkt zum Bogenzentrum in Y
                        # Skizze: http://www.linuxcnc.org/docview/html//gcode_main.html#sub:G2,-G3:-Arc

                        #print ("zeilen mit kreis "  )
                        
                        indexx  = find(zeile,"X")
                        indexy = find(zeile,"Y")
                        indexj = find(zeile,"J")
                        indexf = find(zeile,"F")

                        if ( (indexx) != -1):
                         x= float(zeile[indexx+1:indexy])
                        #print ("x= %f " % x )
                        if ( (indexy) != -1):
                         y= float(zeile[indexy+1:indexi])
                        #print ("y= %f " % y )
                        if ( (indexj) != -1): 
                         i= float( zeile[indexi+1:indexj])
                        else:
                         i= float( zeile[indexi+1:indexf])
                        #print ("i= %f " % i )
                        if ( (indexj) != -1):
                          j= float(zeile[indexj+1:indexf])
                        else :
                          j=0
                        #print ("j= %f " % j )


                        centx=xalt+i
                        #print ("centx= %f " % centx )
                        centy=yalt+j
                        #print ("centy= %f " % centy )

                        aX= xalt-centx
                        #print ("ax= %f " % aX )
                        aY= yalt-centy
                        #print ("ay= %f " % aY )
                        bX= x-centx
                        #print ("bx= %f " % bX )
                        bY= y-centy
                        #print ("by= %f " % bY )
                        
                        indexg  = find(zeile,"G")
                        g= zeile[indexg:indexg+3]
                        #print g

                        if ((g == "G02")or (g=="G2 ")):
                          angleA = math.atan2(bY, bX)
                          angleB = math.atan2(aY, aX)
                        else :
                          angleA = math.atan2(aY, aX)
                          angleB = math.atan2(bY, bX)

                        if (angleB <= angleA):
                          angleB += 2*math.pi;
                        angle = angleB - angleA;
                 
                        #print ("angleA= %f " % angleA )
                        #print ("angleB= %f " % angleB )
 
                        radius = math.sqrt(aX * aX + aY * aY)
                        length = radius * angle;

                        #print ("radius= %f " % radius )
                        #print ("length= %f " % length )

                        steps = int(max(angle * 2.4, length / 0.5));
                        #print ("steps= %i " % steps )

                        #xaltpix=math.trunc((xalt+xmin)*masstab)
                        #yaltpix=math.trunc((yalt+ymin)*masstab)

                        #xtempaltpix=xaltpix
                        #ytempaltpix=yaltpix

                        for s in range(1,steps):
                          step = s
                          if ( (g == "G02") or (g=="G2 ")) :
                            step = steps - s
                          xtemp = centx + radius * math.cos(angleA + angle	* ( float(step) / steps))
                          ytemp = centy + radius * math.sin(angleA + angle * ( float(step) / steps))

                          # in bildschirmkoordinaten uebersetzen

                          #xtemppix=math.trunc((xtemp+xmin)*masstab)
                          #ytemppix=math.trunc((ytemp+ymin)*masstab)

                          # widget.window.draw_line(xgc,xtempaltpix,ytempaltpix,xtemppix,ytemppix)

                          element[aline].append(pos=(xtemp,ytemp,z))

                          #xtempaltpix=xtemppix
                          #ytempaltpix=ytemppix

 
                        xalt=x
                        yalt=y
                        zalt=z
                        #xaltpix=xpix
                        #yaltpix=ypix

                         
                       else:
                      # Linie zeichnen
                        #print "linie Zeichnen"
                        #print zeile

                        tempzeile=zeile
                        indexz = find(tempzeile,"Z")
                        if ( (indexz) != -1):
                         z= float(tempzeile[indexz+1:-1])
                         tempzeile = tempzeile[0:indexz]
                         #tz = text(text="%.0f " %z,pos=(-2,-2,z),height=2)
                        indexy = find(tempzeile,"Y")
                        if ( (indexy) != -1):
                         y= float(tempzeile[indexy+1:-1])
                         tempzeile = tempzeile[0:indexy]
                        indexx = find(tempzeile,"X")
                        if ( (indexx) != -1):
                         x= float(tempzeile[indexx+1:-1])

                        #print ("xalt= %f " % xalt )
                        #print ("yalt= %f " % yalt )
                        #print ("x= %f " % x )
                        #print ("y= %f " % y )
                        #print ("z= %f " % z )
                        #print ("________________")
##
##                        if z<0 :
##                          xgc.set_rgb_fg_color(gtk.gdk.Color(0,0,0))     # black
##                          xgc.line_width = 1
##                        else :
##                          xgc.set_rgb_fg_color(gtk.gdk.color_parse("yellow"))
##                          xgc.line_width = 2
##                          
##  
##                        xaltpix=math.trunc((xalt+xmin)*masstab)
##                        yaltpix=math.trunc((yalt+ymin)*masstab)
##                        xpix=math.trunc((x+xmin)*masstab)
##                        ypix=math.trunc((y+ymin)*masstab)
##                        widget.window.draw_line(xgc,xaltpix,yaltpix,xpix,ypix)
##

                       element[aline].append(pos=(x,y,z))
                       #textkoordinate= text(text=" %.0f,  " %x+" %.0f,  " %y+" %.0f,  " %z,pos=(x,y,z),height=0.2)
                       xalt=x
                       yalt=y
                       zalt=z
                       # end else linie zeichnen

##                      pause= True
##                      while pause: 
##                       rate(50)
##                       if  scene2.kb.keys:
##                        k = scene2.kb.getkey()
##                        pause=False
##                       if scene2.mouse.clicked:
##                        m = scene2.mouse.getclick()
##                        scene2.center=m.pos
##                  
##                      stext.visible=False
                       
                      templine += 1
 
                      
##                
##    
##               # end while
 
           mausklick = mclick(1)  #thread starten
                                  # zentriert das bild mit linker maustaste
           mausklick.start()

           # end Zeichnen

              
                                               
        def G82_ersetzen(self,file_name) :
           
               #print "G82 ersetzen"
               #print ( " in file "+file_name)
               file = open(file_name,'r')
               Seite = file.readlines()
               nlines = len(Seite) 
               file.close()
               zhoch=0
               ztief=0
               templine = 0
             
  
               file = open(file_name, 'w')            
               
                  
               while ((templine < nlines) ):
                      zeile = Seite[templine] 
                      aline=templine+1
                      #print ("zeilen nr= %i " % aline )
                      #print zeile
                      tempzeile=zeile

                      #  wegkuerzen
                      index  = find(tempzeile,"F")
                      if ( (index) != -1):
                           tempzeile = tempzeile[0:index]
                           #print " weggekuerzt = " +tempzeile

                      indexz = find(tempzeile,"Z")
                      if ( (indexz) != -1):
                        zhochtemp= float(tempzeile[indexz+1:-1])
                        if zhochtemp>zhoch :
                            zhoch = zhochtemp
                        #print ("zhoch= %f " % zhoch )

                      if (zeile.find("G82") != -1):
                          #print " G82 gefunden"
  
                          indexz = find(tempzeile,"Z")
                          if (indexz != -1):
                            ztief= float(tempzeile[indexz+1:-1])
                            #print ("ztief= %f " % ztief )
                            tempzeile = tempzeile[0:indexz]

                          zeile="G00 "+tempzeile[ 3:-1]+"\n"
                          file.write(zeile)

                          zeile = ("G00 Z%f " % ztief+"\n")
                          file.write(zeile)

                          

                          zeile= "G00 Z%f " % zhoch+"\n"
                    
                      # ende if G82

                      file.write(zeile)
                        
                      
                      templine += 1
                     
                        
               file.close()

#ende G82 ersetzen

        def R_ersetzen(self,file_name) :
           
               #print "r ersetzen"
               #print ( " in file "+file_name)
               file = open(file_name,'r')
               Seite = file.readlines()
               nlines = len(Seite) 
               file.close()
               x=0
               y=0
               xalt=0
               yalt=0
               z=0
               templine = 0
             
  
               file = open(file_name, 'w')            
               
                  
               while ((templine < nlines) ):
                      zeile = Seite[templine] 
                      aline=templine+1
                      #print ("zeilen nr= %i " % aline )
                      #print zeile
                      tempzeile=zeile
                      rechenfehler = False
                      fgefunden=False

                       # S wegkuerzen
                      indexs  = find(tempzeile,"S")
                      if ( (indexs) != -1):
                         tempzeile = tempzeile[0:indexs]+"\n"
 

                      # M funktion wegkuerzen
                      indexm  = find(tempzeile,"M")
                      if ( (indexm) != -1):
                           tempzeile = zeile[0:indexm]+"\n"

                      # F 
                      indexf  = find(tempzeile,"F")
                      if ( (indexf) != -1):
                           fgefunden=True
                           f= float(tempzeile[indexf+1:-1])
                           tempzeile = tempzeile[0:indexf]+"\n"
                          
 
                      indexr  = find(tempzeile,"R")
                      if ( (indexr) != -1):
                         r= float(tempzeile[indexr+1:-1])
                         #print ("r= %f " % r )
                         
                         tempzeile = tempzeile[0:indexr]
                         indexy = find(zeile,"Y")
                         if ( (indexy) != -1):
                          y= float(tempzeile[indexy+1:-1])
                          tempzeile = tempzeile[0:indexy]
                         else: y = yalt 

                         indexx = find(tempzeile,"X")
                         if ( (indexx) != -1):
                          x= float(tempzeile[indexx+1:-1])

                         #print ("xalt= %f " % xalt )
                         #print ("yalt= %f " % yalt )
                         #print ("x= %f " % x )
                         #print ("y= %f " % y )

                         ax= x-xalt
                         ay= y-yalt

                         #print ("ax= %f " % ax )
                         #print ("ay= %f " % ay )
           
                         
                         s = math.sqrt(ax * ax + ay * ay)

                         #print ("s= %f " % s )

                         indexg  = find(tempzeile,"G")
                         if ( (indexg) != -1):
                          g= tempzeile[indexg:indexg+3]
                         #print g
                         try :
                          angle1 = math.acos((s/2)/r)
                          angle2 = math.atan2(ay,ax)
                          angle2grad=(angle2*180/math.pi)
                   
                          #print ("angle2= %f " % angle2grad)
                          angle1grad=(angle1*180/math.pi)
                          #print ("angle1= %f " % angle1grad)

                          angle3=angle2-angle1
                         except :
                           print ( "Rechenfehler")
                           print ("zeilen nr= %i " % aline )
                           print zeile
                           rechenfehler = True

                         if not rechenfehler :
                          if  ((g == "G02") or (g=="G2 ")):
                           g= "G02"
                           #print "g2 rum"
                           i=r*math.cos(angle3)
                           j=r*math.sin(angle3)

                           if ((angle2grad<=-80) and (angle2grad> -90)) :
                             #print ("Fall g02 1 \n")
                             i= (r*math.cos(angle3))
                             j= (r*math.sin(angle3))


                           if ((angle2grad<=-90) and (angle2grad> -180)) :
                             #print ("Fall g02 2 \n")                            
                             i= (r*math.cos(angle3))
                             j=(r*math.sin(angle3))

                           if ((angle2grad<=0) and (angle2grad > -80)) :
                             #print ("Fall g02 3 \n")                            
                             i= (r*math.cos(angle3))
                             j=(r*math.sin(angle3))
  

                          else :
                           g= "G03"
                           
                           #print "g3 rum "
                              
                           j=r*math.cos(angle3)
                           i=r*math.sin(angle3)


                           if ((angle2grad<=0) and (angle2grad> -90)) :
                             #print ("Fall1")                            
                             i=(r*math.cos(angle3))
                             j=-r*math.sin(angle3)
                             
                           if ((angle2grad<=0) and (angle2grad> -90) and
                               (angle1grad==45)) :
                             #print ("Fall1b")                            
                             j=(r*math.cos(angle3))
                             i=-r*math.sin(angle3)
                             
                           if (angle2grad>90) and (angle2grad<180):
                             #print ("Fall2")     
                             i=r*math.cos(angle3)
                             j=-(r*math.sin(angle3))
                             
                           if (angle2grad>90) and (angle2grad<180)and (angle1grad> 15) and (angle1grad<90) :
                             #print ("Fall2b")     
                             i=(r*math.cos(angle3))
                             j=(r*math.sin(angle3))
                             
                           if ((angle2grad>90) and (angle2grad<180)and
                              (angle1grad== 45)  ):
                             #print ("Fall2c")     
                             j=(r*math.cos(angle3))
                             i=-(r*math.sin(angle3))
                             
                           if ((angle2grad> -180) and (angle2grad < -90)):
                             #print ("Fall3")     
                             i=(r*math.cos(angle3))
                             j=(r*math.sin(angle3))

                             
                           if ( (angle2grad> -180) and (angle2grad < -90) and
                              (angle1grad==45)) :

                             #print ("Fall3b")     
                             j=(r*math.cos(angle3))
                             i=(r*math.sin(angle3))


            
                          #print ("I= %f " % i)
                          #print ("J= %f " % j)
                          #print"----------------------------------------"

                          #   G2 durch G02 ersetzten!!!! sonst schlecht fuer interpreter arduino
                          if fgefunden :
                               zeile = g+" X%f " %x+" Y%f " %y+" I%f " %i+"J%f " %j+" F%f" %f + "\n"
                          else :
                              zeile = g+" X%f " %x+" Y%f " %y+" I%f " %i+"J%f " %j+"\n"

                          #print zeile
                          xalt=x
                          yalt=y
                       # ende if "R" in zeile

                      if not rechenfehler :
                        file.write(zeile)

                      indexz = find(tempzeile,"Z")
                      if ( (indexz) != -1):
                       tempzeile = tempzeile[0:indexz]
                      indexy = find(tempzeile,"Y")
                      if ( (indexy) != -1):
                        yalt= float(tempzeile[indexy+1:-1])
                        tempzeile = tempzeile[0:indexy]
                      indexx = find(tempzeile,"X")
                      if ( (indexx) != -1):
                        xalt= float(tempzeile[indexx+1:-1])

  
                      templine += 1
                     
                        
               file.close()
# ende R ersetzten               
             
 		
        def browse_for_file(self):

                file_open = gtk.FileChooserDialog(title="Select gcode"
                                , action=gtk.FILE_CHOOSER_ACTION_OPEN
                                , buttons=(gtk.STOCK_CANCEL
                                , gtk.RESPONSE_CANCEL
                                , gtk.STOCK_OPEN
                                , gtk.RESPONSE_OK))
		
                result = ""

                if file_open.run() == gtk.RESPONSE_OK:
                        result = file_open.get_filename()
                        file_open.destroy()

                return result
      
        def on_xplus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False
               commando='G0 X1 \n' 
               send_line(commando)

        def on_xminus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False
 
               commando='G0 X-1 \n' 
               send_line(commando)

        def on_yplus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False

               commando='G0 Y1 \n' 
               send_line(commando)

        def on_yminus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False
               commando='G0 Y-1 \n' 
               send_line(commando)

        def on_zplus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False
               commando='G0 Z1 \n' 
               send_line(commando)

        def on_zminus_clicked(self, widget):
               global G90gesendet
               if G90gesendet:
                 commando='G91 \n' 
                 send_line(commando)
                 G90gesendet=False
               commando='G0 Z-1 \n' 
               send_line(commando)

        def on_makehome_clicked(self, widget):
               commando='G92 \n' 
               send_line(commando)      

        def on_go_button_clicked(self, widget):
               c=self.commando.get_text()+'\n'
               if (strip(c)) :
                send_line(c)           
              
        def On_Delete(self, widget):
              gdk.threads_leave()
              Worker.Quit(self)
              gdk.threads_enter()
              gtk.main_quit()
              return False

        def power_clicked(self, widget):
                       
              b=widget.get_active()
              # um das haeckchen zu setzen set_active(true)
     
              if b :
               zeige_info(" Power an \n")
               commando='M8 \n' 
               send_line(commando)
              else :
               zeige_info(" Power aus \n")
               commando='M5 \n' 
               send_line(commando)
 



gdk.threads_init()
          
if __name__ == "__main__":

        gcode = pygcode()
        gtk.main()
      

    

